package ca.uwindsor.cs.deepweb.utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.zip.GZIPInputStream;

public class GZipDecompressor {

	protected String workingdirectory;

	protected File decompressedfile;

	/**
	 * @param workingdirectory
	 *            The directory to save decompressed file
	 */
	public GZipDecompressor(String workingdirectory) {
		this.workingdirectory = workingdirectory;
	}

	public void decompress(File gzfile) throws FileNotFoundException,
			IOException {
		// Open the compressed file
		// String inFilename = "infile.gzip";
		GZIPInputStream in = new GZIPInputStream(new FileInputStream(gzfile));

		// Open the output file
		decompressedfile = new File(workingdirectory + File.separator
				+ gzfile.getName().replace(".gz", ""));
		OutputStream out = new FileOutputStream(decompressedfile);

		// Transfer bytes from the compressed file to the output file
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}

		// Close the file and stream
		in.close();
		out.close();

	}

	public File getDecompressedFile() {
		return decompressedfile;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		args = new String[1];
		args[0] = "";
		// TODO Auto-generated method stub
		long startTime = new Date().getTime();
		try {
			// Open the compressed file
			// String inFilename = "infile.gzip";
			GZIPInputStream in = new GZIPInputStream(new FileInputStream(
					args[0]));

			// Open the output file
			String outFilename = "d:\\temp";
			OutputStream out = new FileOutputStream(outFilename);

			// Transfer bytes from the compressed file to the output file
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

			// Close the file and stream
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long endTime = new Date().getTime();

		System.out.println("It takes " + (endTime - startTime)
				+ " milliseconds to extrat the files from" + args[0]);
	}

}
